// utils
const jwt = require("jsonwebtoken")
const PRIVATE_KEY = "member serve"

// modules
const AdminModule = require('../models/tableModels/adminModule.js')

// methods
const response = require('../utils/methods/response.js')

// 管理员控制器
const adminController = {
    /**
     * 登录
     * */
    login: async ({ query }, res) => {
        try {
        // 获取请求参数
            const { username, password } = query
            // 查询数据库数据
            const data = await AdminModule.knexSelectFiledRow({ username })
            if (data.length) {
                const result = data[0]
                if (password === result.password) {
                    delete result.password
                    const token = jwt.sign({
                        id: result.id
                    }, PRIVATE_KEY, {
                        expiresIn: 60 * 60 * 4
                    })
                    response.success(res, { userInfo: result, token })
                } else {
                    response.fail(res, '密码错误！')
                }
            } else {
                response.fail(res, '未查找此用户！')
            }
        } catch(err) {
            response.error(res, err)
        }
    },
    /**
     * 修改密码
     * */
    changePwd: async ({ body }, res) => {
        try {
            const { oldPwd, newPwd, id } = body
            // 查询数据库数据
            const data = await AdminModule.knexSelectFiledRow({ id })
            if (data.length) {
                // 如果原密码正确更新
                if (oldPwd === data[0].password) {
                    await AdminModule.update({ id }, { password: newPwd })
                    response.success(res)
                } else {
                    response.fail(res, '原密码错误！')
                }
            }
        } catch(err) {
            response.error(res, err)
        }
    },
    /**
     * 更新账户信息
     * */
    updateAccountInfo: async ({ body }, res) => {
        try {
            const { systemImgUrl, adminName, adminPhone, companyEntity, id } = body
            // 需要更新的数据
            const updateData = systemImgUrl ? { systemImgUrl } : { adminName, adminPhone, companyEntity }
            // 更新数据
            const data = await AdminModule.update({ id }, updateData)
            if (data) {
                const result = await AdminModule.knexSelectFiledRow({ id })
                delete result.password
                response.success(res, result[0])
            } else {
                response.fail(res, '未查找此用户！')
            }
        } catch(err) {
            response.error(res, err)
        }
    }
}

module.exports = adminController
